

Rem
	bbdoc: Game2D entity manager
	about: Holds, updates and renders entities.
endrem
Type TEntityManager

	rem
		bbdoc: The singleton instance of the class
	endrem
	Global _singletonInstance:TEntityManager

	'main list of all entities in the manager
	Field _entities:TList

	'entities, per render layer
	'each index in the layer holds a list of entities for that layer
	Field _layers:TBag


	Rem
		bbdoc:   Constructor
		about:   Do not use this method, but GetInstance() instead
		returns:
	EndRem
	Method New()
		if _singletonInstance <> Null then Throw("You can only create one instance of this singleton!")
		_singletonInstance = Self
		_entities = new TList
		_layers = new TBag
	EndMethod


	Rem
		bbdoc:   Returns the instance of this singleton
		about:   Creates a new instance when no instance is present
		returns: TEntityManager
	EndRem
	Function GetInstance:TEntityManager()
		If Not _singletonInstance
			Return New TEntityManager
		Else
			Return _singletonInstance
		EndIf
	EndFunction


	Rem
		bbdoc:   Destroys this singleton
		about:
		returns:
	EndRem
	Method Destroy()
		_singletonInstance = Null
	End Method



	Rem
		bbdoc:   Removes all entities and renderlayers from the manager
		about:
		returns:
	EndRem
	Method Clear()
		_entities.Clear()
		_layers.Clear()
	End Method



	Rem
		bbdoc:   Adds specified entity to layer with passed id
		about:   The render layer is created when passed id is not found
		returns:
	EndRem
	Method AddEntity(e:TEntity, layer:Int)
		_entities.AddLast(e)
		Local l:TList = TList(_layers.Get(layer))
		If Not l
			l = New TList
			_layers.Set(layer, l)
		End If
		l.AddLast(e)
		e.SetRenderLayer(layer)
	End Method



	Rem
		bbdoc:   Removes specified entity from the manager
		about:
		returns:
	EndRem
	Method RemoveEntity(e:TEntity)
		_entities.Remove(e)
		Local l:TList = TList(_layers.Get(e.GetRenderLayer()))
		l.Remove(e)
	End Method



	Rem
		bbdoc:   Updates all entites in the manager
		about:
		returns:
	EndRem
	Method Update()
		For local e:TEntity = eachin _entities
			e.Update()
		Next
	End Method


	'renders entities in the renderlayers.
	'start with layer 0
	Rem
		bbdoc:   Renders all entities in the manager
		about:
		returns:
	EndRem
	Method Render(tween:Double)
        Local amount:Int=0
		For Local index:Int = 0 To _layers.GetSize() - 1
			Local l:TList = TList(_layers.Get(index))
			If l
				For Local e:TEntity = EachIn l
					e.Render(tween)
	                amount:+1
				Next
			Endif
		Next
		?debug
        DrawText("entities " + amount, 0,0)
		?
	End Method

End Type